package com.foreknow.demo13;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PreparedStatementDemo {
    public static void main(String[] args) {
        try {
            //1.加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取链接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true","root","root");
            //3.获取Statement
            PreparedStatement pstmt = conn.prepareStatement("select * from employee where username = ? and password = ?");
            //将？替换为具体的值
//            pstmt.setString(1,"fender");
//            pstmt.setString(2,"123456");
            //4.执行查询
            ResultSet rs = pstmt.executeQuery();
            List<Employee> list= new ArrayList<>();
            while(rs.next()){
                Employee e = new Employee();
                e.setId(rs.getInt("id"));
                e.setUsername(rs.getString("username"));
                e.setPassword(rs.getString("password"));
                list.add(e);
            }
            for (Employee e:list
            ) {
                System.out.println(e.getId()+" "+e.getUsername()+" "+e.getPassword());
            }
            //5.释放资源
            rs.close();
            pstmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
